<template>
  <div class="address-edit">
    <PageHeader :title="isEdit ? '编辑地址' : '新增地址'" />

    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="form.name"
          name="name"
          label="收货人"
          placeholder="请输入收货人姓名"
          :rules="[{ required: true, message: '请输入收货人姓名' }]"
        />

        <van-field
          v-model="form.phone"
          name="phone"
          label="手机号码"
          placeholder="请输入手机号码"
          :rules="[
            { required: true, message: '请输入手机号码' },
            { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确' }
          ]"
        />

        <van-field
          readonly
          clickable
          name="area"
          label="所在地区"
          v-model="areaText"
          placeholder="请选择所在地区"
          @click="showAreaPicker = true"
          :rules="[{ required: true, message: '请选择所在地区' }]"
        />

        <van-popup v-model:show="showAreaPicker" round position="bottom">
          <van-area
            :area-list="areaList"
            @confirm="onAreaConfirm"
            @cancel="showAreaPicker = false"
          />
        </van-popup>

        <van-field
          v-model="form.detail"
          name="detail"
          label="详细地址"
          type="textarea"
          placeholder="请输入详细地址"
          :rules="[{ required: true, message: '请输入详细地址' }]"
          rows="2"
          autosize
        />

        <van-cell title="设为默认地址" center>
          <template #right-icon>
            <van-switch v-model="form.isDefault" size="24" />
          </template>
        </van-cell>
      </van-cell-group>

      <div class="submit-btn">
        <van-button round block type="primary" native-type="submit" :loading="submitting">保存</van-button>
      </div>

      <div class="delete-btn" v-if="isEdit">
        <van-button round block type="danger" plain @click="onDelete" :loading="deleting">删除</van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showSuccessToast, showFailToast, showDialog } from 'vant'
import PageHeader from '@/components/PageHeader.vue'
import { areaList } from '@vant/area-data'
import {
  getAddressDetail,
  addAddress,
  updateAddress,
  deleteAddress as deleteAddressApi,
} from '@/api/address'

const router = useRouter()
const route = useRoute()

// 表单数据
const form = reactive({
  id: undefined as number | undefined,
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detail: '',
  isDefault: false,
})

// 状态控制
const submitting = ref(false)
const deleting = ref(false)
const showAreaPicker = ref(false)

// 是否为编辑模式
const isEdit = computed(() => !!form.id)

// 地区显示文本
const areaText = computed(() => {
  if (form.province && form.city && form.district) {
    return `${form.province} ${form.city} ${form.district}`
  }
  return ''
})

// 初始化数据
onMounted(async () => {
  const id = route.query.id
  if (id) {
    await fetchAddressDetail(Number(id))
  }
})

// 获取地址详情
const fetchAddressDetail = async (id: number) => {
  try {
    const res = await getAddressDetail(id)
    if (res.code === 200 && res.data) {
      const data = res.data
      Object.assign(form, {
        id: data.id,
        name: data.name,
        phone: data.phone,
        province: data.province,
        city: data.city,
        district: data.district,
        detail: data.detail,
        isDefault: data.isDefault,
      })
    }
  } catch (error) {
    console.error('获取地址详情失败:', error)
    showFailToast('获取地址详情失败')
  }
}

// 地区选择确认
const onAreaConfirm = (values: any) => {
  console.log(values)
  let target = values.selectedOptions || []
  // 检查数据有效性
  if (!target || target.length < 3) {
    showToast('地区数据不完整，请重新选择')
    showAreaPicker.value = false
    return
  }

  // 安全获取地区名称
  const province = target[0]?.text || ''
  const city = target[1]?.text || ''
  const district = target[2]?.text || ''

  // 检查所有地区值是否都有
  if (!province || !city || !district) {
    showToast('请选择完整的省市区信息')
    return
  }

  form.province = province
  form.city = city
  form.district = district
  showAreaPicker.value = false
  console.log(areaText)
}

// 提交表单
const onSubmit = async () => {
  submitting.value = true

  try {
    const addressData = {
      ...form,
    }

    let res
    if (isEdit.value) {
      // 编辑地址
      res = await updateAddress(form.id as number, addressData)
    } else {
      // 新增地址
      res = await addAddress(addressData)
    }

    if (res.code === 200) {
      showSuccessToast(isEdit.value ? '地址更新成功' : '地址添加成功')
      router.back()
    } else {
      showFailToast(res.message || '操作失败')
    }
  } catch (error) {
    console.error('保存地址失败:', error)
    showFailToast('保存地址失败')
  } finally {
    submitting.value = false
  }
}

// 删除地址
const onDelete = async () => {
  try {
    await showDialog({
      title: '删除地址',
      message: '确定要删除该地址吗？',
      showCancelButton: true,
    })

    deleting.value = true
    const res = await deleteAddressApi(form.id as number)

    if (res.code === 200) {
      showSuccessToast('地址删除成功')
      router.back()
    } else {
      showFailToast(res.message || '删除失败')
    }
  } catch (error) {
    console.error('删除地址失败:', error)
  } finally {
    deleting.value = false
  }
}
</script>

<style scoped lang="scss">
.address-edit {
  min-height: 100vh;
  background-color: $background-color;
}

.submit-btn,
.delete-btn {
  margin: $padding-xl $padding-lg;
}

.delete-btn {
  margin-top: 0;
}
</style> 